package java01;

import org.junit.Test;

import java.util.*;

public class ListTest {

    @Test
    public void listTest01(){
        new ArrayDeque<>();//基于队列
        ArrayList<String> list = new ArrayList<String>(){{add("str");add("lisi.txt");add("zhangsan");add("wangwu");}};//基于数组

        Iterator<String> iterator = list.iterator();
        System.out.println(iterator.next());//调用next时，迭代器越过下一个元素，并返回刚刚越过元素的引用
        System.out.println("----------------");
        iterator.remove();//remove前不调用next是不合法的
        iterator.forEachRemaining(element -> System.out.println(element));//JavaSE8中迭代器的lambda表达式

        System.out.println("----------------");
        list.removeIf(s -> s.endsWith(".txt"));//删除满足条件的元素
        System.out.println(Arrays.toString(list.toArray()));
        list.retainAll(new ArrayList<String>(){{add("wangwu");}});//删除与other集合中元素不同的元素，保留交集
        System.out.println(Arrays.toString(list.toArray()));
    }

    @Test
    public void listTest02(){
        ArrayList<String> list = new ArrayList<String>(){{add("str");add("lisi.txt");add("zhangsan");add("wangwu");}};
        ListIterator<String> iterator = list.listIterator();
        ListIterator<String> iterator2 = list.listIterator(3);//返回index元素前的元素
        String next = iterator.next();//下一个
        System.out.println(next);
        iterator.set("666");//设置当前位置值
        String previous = iterator.previous();//上一个
        System.out.println(previous);

        iterator.next();
        int i = iterator.nextIndex();//查看下一个元素索引，效率高，因为迭代器保持着当前位置的计数值
        System.out.println(i);
        iterator.remove();
//        iterator2.next();//iterator修改了集合，iterator2会抛出ConcurrentModificationException异常
    }
}
